package com.practice.concurrency;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class BlockingQueueMain {

	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {
			service.submit(new BlockingQueueCommand(i));
		}
		
		Runnable command = new Runnable() {
			@Override
			public void run() {
				try {
					while (true) {
						Thread.sleep((int)(Math.random() * 1000));
						if (BlockingQueueCommand.queue.isEmpty()) {
							break;
						}
						String str = BlockingQueueCommand.queue.take();
						System.out.println(str + " has been taken");
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		};
		service.submit(command);
		service.shutdown();
	}

}

class BlockingQueueCommand implements Runnable {
	protected static BlockingQueue<String> queue = new LinkedBlockingQueue<String>(3);
	
	private int index;
	public BlockingQueueCommand(int id) {
		this.index = id;
	}
	
	@Override
	public void run() {
		try {
			queue.put(String.valueOf(this.index));
			System.out.println("[" + this.index + "] in queue");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}